package org.csu.onlineedubackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.onlineedubackend.dto.CommentReplyTreeDTO;
import org.csu.onlineedubackend.entity.CommentReply;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.service.CommentReplyService;
import org.csu.onlineedubackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/comment")
public class CommentReplyController {

    @Autowired
    private CommentReplyService commentReplyService;
    @Autowired
    private UserService userService;

    @PostMapping("/reply")
    public CommonResponse<?> addReply(@RequestBody CommentReply reply) {
        commentReplyService.save(reply);
        return CommonResponse.createForSuccess(0, "回复成功", reply);
    }

    @GetMapping("/{commentId}/replies")
    public List<CommentReplyTreeDTO> getReplies(@PathVariable Integer commentId) {
        List<CommentReply> all = commentReplyService.list(
                new QueryWrapper<CommentReply>().eq("comment_id", commentId).orderByAsc("created_at")
        );
        // 批量查所有涉及到的userId
        Set<Integer> userIds = all.stream().map(CommentReply::getUserId).collect(Collectors.toSet());
        Map<Integer, String> userNameMap = userService.getUserNamesByIds(userIds);

        Map<Integer, CommentReplyTreeDTO> map = new HashMap<>();
        List<CommentReplyTreeDTO> roots = new ArrayList<>();
        for (CommentReply r : all) {
            String userName = userNameMap.getOrDefault(r.getUserId(), "用户");
            CommentReplyTreeDTO dto = new CommentReplyTreeDTO(r, userName);
            map.put(r.getId(), dto);
        }
        for (CommentReply r : all) {
            if (r.getParentReplyId() == null) {
                roots.add(map.get(r.getId()));
            } else {
                CommentReplyTreeDTO parent = map.get(r.getParentReplyId());
                if (parent != null) {
                    parent.getChildren().add(map.get(r.getId()));
                }
            }
        }
        return roots;
    }

    @DeleteMapping("/reply/{replyId}")
    public CommonResponse<?> deleteReply(@PathVariable Integer replyId, @RequestParam Integer userId) {

        CommentReply reply = commentReplyService.getById(replyId);
        if (reply == null) {
            return CommonResponse.createForError("回复不存在");
        }
        if (!reply.getUserId().equals(userId)) {
            return CommonResponse.createForError("无权删除他人回复");
        }
        commentReplyService.removeById(replyId);
        return CommonResponse.createForSuccess(0, "删除成功");
    }
}